/**
 * 
 */
package com.nari.heatshare.service;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.nari.baseinfo.dao.IFileMappingDao;
import com.nari.basic.model.IUser;
import com.nari.coreframe.service.GenericServiceImpl;
import com.nari.coreframe.webframe.SysEnvironmentMgr;
import com.nari.ftpclient.business.IRemoteFileManage;
import com.nari.heatshare.dao.IAssignMeterDataFileDao;
import com.nari.heatshare.dao.IAssignMeterDataGatherDao;
import com.nari.heatshare.dao.springjdbc.IAssignMeterDataJdbcDao;
import com.nari.heatshare.model.IAssignMeterDataFile;
import com.nari.heatshare.model.IAssignMeterDataGather;
import com.nari.heatshare.utils.MeterDataTxtParser;
import com.nari.platform.date.CalendarConstants;
import com.nari.platform.date.CalendarUtils;
import com.nari.platform.model.PageCond;
import com.nari.platform.model.ResponseMsg;
import com.nari.platform.model.ResultWithPageCond;
import com.nari.platform.model.WebConstants;

/**
 * 
 * @author Xiaopeng
 * @date 2013-8-18
 */
public class AssignMeterDataFileServiceImpl extends GenericServiceImpl<IAssignMeterDataFile, String>
		implements IAssignMeterDataFileService {
	private String diskFilePath;
	private String meterDataFileFolder;
	private IFileMappingDao iFileMappingDao;
	private IAssignMeterDataGatherDao iAssignMeterDataGatherDao;
	private IAssignMeterDataJdbcDao iAssignMeterDataJdbcDao;
	private IAssignMeterDataStatisticsService iAssignMeterDataStatisticsService;
	private IRemoteFileManage iRemoteFileManage;

	/**
	 * 分页查询分配表数据文件列表
	 * @param fileName 数据文件名(可选)
	 * @param startDate 起始上传日期(可选)
	 * @param endDate 终止上传日期(可选)
	 * @param pageCond
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-9-1
	 */
	public ResultWithPageCond<IAssignMeterDataFile> queryDataFilePage(String fileName, Date startDate, 
			Date endDate, PageCond pageCond) throws Exception {
		IAssignMeterDataFileDao iAssignMeterDataFileDao = (IAssignMeterDataFileDao) this.getiGenericDao();
		return iAssignMeterDataFileDao.queryDataFilePage(fileName, startDate, endDate, pageCond);
	}
	
	/**
	 * 保存上传的分配表数据文件
	 * @param attachFile 数据文件附件
	 * @param fileName 数据文件名
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-9-1
	 */
	public ResponseMsg saveDataFileUpload(File attachFile, String fileName) throws Exception {
		if(attachFile != null) {
			File svFile = null; //存储磁盘附件
			int uploadSymbol = 0;
			IAssignMeterDataFile meterDataFile = null;
			try {
				//附件存储路径对应的磁盘目录检测
				File fileSaveFolder = new File(this.diskFilePath+"/"+this.meterDataFileFolder);
				if(!fileSaveFolder.exists()) fileSaveFolder.mkdirs();
				//文件的存储路径(相对路径)
				String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
				String saveFileName = "manualUploadTxt_"+CalendarUtils.parseDateToString(new Date(), CalendarConstants.dateTimeMiliPreciseFormat_stamp)+ "." + suffix;
				String savePath = this.meterDataFileFolder + "/" + saveFileName;
				//将附件文件保存到磁盘中
				svFile = new File(this.diskFilePath + "/" + savePath);
				uploadSymbol = this.iFileMappingDao.saveUpload(attachFile, svFile);
				//分配表数据文件实体
				meterDataFile = new IAssignMeterDataFile();
				meterDataFile.setFileName(fileName);
				meterDataFile.setFileSize(attachFile.length());
				IUser sysLoginUser = (IUser) SysEnvironmentMgr.getSessionInstance().getAttribute(WebConstants.USER_SESSION);
				meterDataFile.setUploadMan(sysLoginUser.getUserID());
				meterDataFile.setUploadDate(new Date());
				meterDataFile.setDiskID(this.diskFilePath);
				meterDataFile.setSaveUrl(savePath);
				String dataFileUID = this.getiGenericDao().saveEntity(meterDataFile);
				//解析上传的数据文件
				List<IAssignMeterDataGather> meterDataList = null;
				while(true) {
					//文件流上传完成
					if(uploadSymbol > 0) {
						meterDataList = MeterDataTxtParser.parseTxtMeterData(meterDataFile);
						break;
					}
				}
				if(meterDataList == null) {
					//读取的分配表记录数
					meterDataFile.setAmRecordNum(0);
				} else {
					//读取的分配表记录数
					meterDataFile.setAmRecordNum(meterDataList.size());
					//批量新增分配表数据，任务批次信息默认取第一条数据
					String concentratorNo = meterDataList.get(0).getConcentratorNo();
					Date recordTime = meterDataList.get(0).getRecordTime();
					ResponseMsg amSaveMsg = this.iAssignMeterDataStatisticsService.saveMeterDataBatch(meterDataList, 
							concentratorNo, recordTime, dataFileUID, 1); //txt上传解析数据
					if(amSaveMsg.isSuccess()) {
						//分配表数据上传成功数
						meterDataFile.setAmSuccessNum(new Integer(amSaveMsg.getMsg()));
					} else {
						return amSaveMsg;
					}
				}
				this.getiGenericDao().updateEntity(meterDataFile, meterDataFile.getId());
				//将痕迹文件存储到FTP服务器
				iRemoteFileManage.uploadFile("", saveFileName, meterDataFile.getDiskID()+"/"+meterDataFile.getSaveUrl());
			} catch (Exception e) {
				e.printStackTrace();
				if(svFile.exists()) svFile.delete();
				//删除FTP远程文件
				String saveFileName = meterDataFile.getSaveUrl().substring(meterDataFile.getSaveUrl().lastIndexOf("/")+1);
				iRemoteFileManage.removeRemoteFile("", saveFileName);
				throw new Exception(e.getMessage());
			}
			return ResponseMsg.getInstance(true, "");
		}
		return ResponseMsg.getInstance(false, "无法识别的数据文件，请重新上传！");
	}
	
	/**
	 * 根据唯一标识删除分配表数据文件
	 * @param dataFileUID
	 * @return
	 * @throws Exception
	 * @author Xiaopeng
	 * @date 2013-9-1
	 */
	public ResponseMsg deleteDataFileByUID(String dataFileUID) throws Exception {
		IAssignMeterDataFile meterDataFile = this.getiGenericDao().queryEntityById(dataFileUID);
		//文件上传数据的任务批次信息
		List<Map<String, String>> uploadBatchList = this.iAssignMeterDataJdbcDao.queryUploadBatchByDataFileUID(dataFileUID);
		//删除对应的分配表数据
		this.iAssignMeterDataGatherDao.deleteMeterDataByFileID(dataFileUID);
		//更新任务批次统计信息
		if(uploadBatchList!=null && uploadBatchList.size()>0) {
			for(Map<String, String> uploadBatch: uploadBatchList) {
				//任务标识信息
				String concentratorNo = uploadBatch.get("concentratorNo");
				Date recordTime = CalendarUtils.parseStringToDate(uploadBatch.get("recordTime"));
				//数据清空状态下不再执行批次任务更新
				int meterDataNum = iAssignMeterDataGatherDao.countMeterDataNumByUploadBatch(concentratorNo, recordTime);
				if(meterDataNum > 0) {
					//更新任务批次
					this.iAssignMeterDataStatisticsService.saveOrUpdateAmdStatis(concentratorNo, recordTime);
				}
			}
		}
		//删除磁盘附件
		File attachFile = new File(meterDataFile.getDiskID()+"/"+meterDataFile.getSaveUrl());
		if(attachFile.exists()) attachFile.delete();
		//删除数据文件实体
		this.getiGenericDao().deleteEntityById(dataFileUID);
		//删除FTP远程文件
		String saveFileName = meterDataFile.getSaveUrl().substring(meterDataFile.getSaveUrl().lastIndexOf("/")+1);
		iRemoteFileManage.removeRemoteFile("", saveFileName);
		return ResponseMsg.getInstance(true, "");
	}

	/**
	 * @return the diskFilePath
	 */
	public String getDiskFilePath() {
		return diskFilePath;
	}

	/**
	 * @param diskFilePath the diskFilePath to set
	 */
	public void setDiskFilePath(String diskFilePath) {
		this.diskFilePath = diskFilePath;
	}

	/**
	 * @return the meterDataFileFolder
	 */
	public String getMeterDataFileFolder() {
		return meterDataFileFolder;
	}

	/**
	 * @param meterDataFileFolder the meterDataFileFolder to set
	 */
	public void setMeterDataFileFolder(String meterDataFileFolder) {
		this.meterDataFileFolder = meterDataFileFolder;
	}

	/**
	 * @return the iFileMappingDao
	 */
	public IFileMappingDao getiFileMappingDao() {
		return iFileMappingDao;
	}

	/**
	 * @param iFileMappingDao the iFileMappingDao to set
	 */
	public void setiFileMappingDao(IFileMappingDao iFileMappingDao) {
		this.iFileMappingDao = iFileMappingDao;
	}

	/**
	 * @return the iAssignMeterDataGatherDao
	 */
	public IAssignMeterDataGatherDao getiAssignMeterDataGatherDao() {
		return iAssignMeterDataGatherDao;
	}

	/**
	 * @param iAssignMeterDataGatherDao the iAssignMeterDataGatherDao to set
	 */
	public void setiAssignMeterDataGatherDao(
			IAssignMeterDataGatherDao iAssignMeterDataGatherDao) {
		this.iAssignMeterDataGatherDao = iAssignMeterDataGatherDao;
	}

	/**
	 * @return the iAssignMeterDataJdbcDao
	 */
	public IAssignMeterDataJdbcDao getiAssignMeterDataJdbcDao() {
		return iAssignMeterDataJdbcDao;
	}

	/**
	 * @param iAssignMeterDataJdbcDao the iAssignMeterDataJdbcDao to set
	 */
	public void setiAssignMeterDataJdbcDao(
			IAssignMeterDataJdbcDao iAssignMeterDataJdbcDao) {
		this.iAssignMeterDataJdbcDao = iAssignMeterDataJdbcDao;
	}

	/**
	 * @return the iAssignMeterDataStatisticsService
	 */
	public IAssignMeterDataStatisticsService getiAssignMeterDataStatisticsService() {
		return iAssignMeterDataStatisticsService;
	}

	/**
	 * @param iAssignMeterDataStatisticsService the iAssignMeterDataStatisticsService to set
	 */
	public void setiAssignMeterDataStatisticsService(
			IAssignMeterDataStatisticsService iAssignMeterDataStatisticsService) {
		this.iAssignMeterDataStatisticsService = iAssignMeterDataStatisticsService;
	}

	/**
	 * @return the iRemoteFileManage
	 */
	public IRemoteFileManage getiRemoteFileManage() {
		return iRemoteFileManage;
	}

	/**
	 * @param iRemoteFileManage the iRemoteFileManage to set
	 */
	public void setiRemoteFileManage(IRemoteFileManage iRemoteFileManage) {
		this.iRemoteFileManage = iRemoteFileManage;
	}
	
}
